/**
 * Copyright 2016 JustWayward Team
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ecy.quadratic.ui.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.ecy.quadratic.api.ComicApi;
import com.ecy.quadratic.beans.BaseResponseBean;
import com.ecy.quadratic.beans.Comment;
import com.ecy.quadratic.beans.CommunityCommentListResponseBean;
import com.ecy.quadratic.beans.PageInfo;
import com.ecy.quadratic.beans.user.User;
import com.ecy.quadratic.reader.api.support.HeaderInterceptor;
import com.ecy.quadratic.reader.api.support.Logger;
import com.ecy.quadratic.reader.api.support.LoggingInterceptor;
import com.ecy.quadratic.reader.base.RxPresenter;
import com.ecy.quadratic.reader.utils.LogUtils;
import com.ecy.quadratic.ui.contract.CommentLikeContract;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @author yuyh.
 * @date 2016/8/3.
 */
public class CommunityCommentPresenter extends RxPresenter<CommentLikeContract.View>
        implements CommentLikeContract.Presenter<CommentLikeContract.View> {

    private Context mContext;
    private ComicApi comicApi;

    @Inject
    public CommunityCommentPresenter(Context mContext, ComicApi comicApi) {
        this.mContext = mContext;
        this.comicApi = comicApi;
    }

    @Override
    public void refresh(String communityId, String page) {
//        String key = StringUtils.creatAcacheKey("communitycomment-list", communityId,page,SettingManager.getInstance().getUserChooseSex());
        Observable<CommunityCommentListResponseBean> fromNetWork = comicApi.getCommunityCommentList(communityId, page);
//                .compose(RxUtil.<CommunityCommentListResponseBean>rxCacheBeanHelper(key));

        //依次检查disk、network
        Subscription rxSubscription = fromNetWork.subscribeOn(Schedulers.io())//Observable.concat(RxUtil.rxCreateDiskObservable(key, CommunityCommentListResponseBean.class), fromNetWork)
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<CommunityCommentListResponseBean, CommunityCommentListResponseBean>() {
                    @Override
                    public CommunityCommentListResponseBean call(CommunityCommentListResponseBean old) {
                        if (old != null && old.getResult() != null && old.getResult().list != null) {
                            for (int i = 0; i < old.getResult().list.size(); i++) {
                                String userJson = old.getResult().list.get(i).user;
                                if (!TextUtils.isEmpty(userJson)) {
                                    try {
                                        User user = new Gson().fromJson(userJson, User.class);
                                        old.getResult().list.get(i).userBean = user;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }

                                String tagsJson = old.getResult().list.get(i).tags;
                                try {
                                    if (!TextUtils.isEmpty(tagsJson)) {
                                        old.getResult().list.get(i).tagsBean = new Gson().fromJson(tagsJson, Comment.Tags.class);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                String imgJson = old.getResult().list.get(i).imgs;
                                try {
                                    if (!TextUtils.isEmpty(imgJson)) {
                                        old.getResult().list.get(i).imagesBean = new Gson().fromJson(imgJson, ArrayList.class);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        }

                        return old;
                    }
                })
                .subscribe(new Observer<CommunityCommentListResponseBean>() {
                    @Override
                    public void onNext(CommunityCommentListResponseBean communityBean) {
                        if (communityBean != null) {
                            PageInfo<Comment> list = communityBean.getResult();
                            if (list != null && mView != null) {
                                mView.showRefreshList(list);
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        mView.complete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("getLastCommunityList", e.toString());
                        mView.showError();
                    }
                });
        addSubscrebe(rxSubscription);
    }


    @Override
    public void postComment(String communityId, String userid, String user, String content) {
        Map<String, String> map = new HashMap<>();
        map.put("communityId", communityId);
        map.put("userid", userid);
        map.put("user", user);
        map.put("content", content);
        Subscription rxSubscription = sendMultipart("http://47.92.90.25/v1/postcommunitycomment", map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Subscriber<BaseResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        mView.showError();
                        LogUtils.i("post", "throwable:" + throwable);
                    }

                    @Override
                    public void onNext(BaseResponseBean s) {

                        if (s != null && s.getStatus() == 100) {
                            mView.postCommentSuccesful();
                        } else {
                            mView.showError();
                        }
                        LogUtils.i("post s,,,", "s:,,," + s.getStatus() + "...");
                    }
                });

        addSubscrebe(rxSubscription);
    }

    /**
     * 上传多张图片及参数
     *
     * @param reqUrl URL地址
     * @param params 参数
     */
    private Observable<BaseResponseBean> sendMultipart(final String reqUrl, final Map<String, String> params) {
        return Observable.create(new Observable.OnSubscribe<BaseResponseBean>() {

            @Override
            public void call(final Subscriber<? super BaseResponseBean> subscriber) {
                MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
                multipartBodyBuilder.setType(MultipartBody.FORM);
                //遍历map中所有参数到builder
                if (params != null) {
                    for (String key : params.keySet()) {
                        multipartBodyBuilder.addFormDataPart(key, params.get(key));
                    }
                }

                //构建请求体
                RequestBody requestBody = multipartBodyBuilder.build();

                Request.Builder RequestBuilder = new Request.Builder();
                RequestBuilder.url(reqUrl);// 添加URL地址
                RequestBuilder.post(requestBody);
                Request request = RequestBuilder.build();
                LoggingInterceptor logging = new LoggingInterceptor(new Logger());
                logging.setLevel(LoggingInterceptor.Level.BODY);
                OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
                        .connectTimeout(20 * 1000, TimeUnit.MILLISECONDS)
                        .readTimeout(20 * 1000, TimeUnit.MILLISECONDS)
                        .retryOnConnectionFailure(true) // 失败重发
                        .addInterceptor(new HeaderInterceptor())
                        .addInterceptor(logging);
                builder.build().newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("****");
                        subscriber.onError(e);
                        subscriber.onCompleted();
                        call.cancel();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
//                        System.out.println(response.body().string());
                        String result = response.body().string();
                        Gson gson = new Gson();
                        BaseResponseBean bean = gson.fromJson(result, BaseResponseBean.class);

                        subscriber.onNext(bean);
                        subscriber.onCompleted();
                        call.cancel();
                    }
                });
            }
        });
    }

    @Override
    public void loadMore(String communityId, String page) {
//        String key = StringUtils.creatAcacheKey("communitycomment-list", communityId,page,SettingManager.getInstance().getUserChooseSex());
        Observable<CommunityCommentListResponseBean> fromNetWork = comicApi.getCommunityCommentList(communityId, page);
//                .compose(RxUtil.<CommunityCommentListResponseBean>rxCacheBeanHelper(key));

        //依次检查disk、network
        Subscription rxSubscription = fromNetWork.subscribeOn(Schedulers.io())//Observable.concat(RxUtil.rxCreateDiskObservable(key, CommunityCommentListResponseBean.class), fromNetWork)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CommunityCommentListResponseBean>() {
                    @Override
                    public void onNext(CommunityCommentListResponseBean recommend) {
                        if (recommend != null) {
                            PageInfo<Comment> list = recommend.getResult();
                            if (list != null && mView != null) {
                                mView.showLoadMoreList(list);
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {
                        mView.complete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("getLastCommunityList", e.toString());
                        mView.showError();
                    }
                });
        addSubscrebe(rxSubscription);
    }

    @Override
    public void postLike(String communityId) {
        Observable<BaseResponseBean> fromNetWork = comicApi.postCommunityLike(communityId);


        //依次检查disk、network
        Subscription rxSubscription = fromNetWork.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponseBean>() {
                    @Override
                    public void onNext(BaseResponseBean communityBean) {
                        if (communityBean != null && communityBean.getStatus() == 100) {
                            mView.postLikeSuccessful();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        mView.complete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("getLastCommunityList", e.toString());
                        mView.showError();
                    }
                });
        addSubscrebe(rxSubscription);
    }
}
